package leetcode.practice;

/**
 * 5. 最长回文子串
 */
public class LongestPalindrome {

    int start = 0;
    int end = 0;
    int maxLen = 1;

    public static void main(String[] args) {
        String ss = "babad";
        System.out.println(new LongestPalindrome().method(ss));

    }

    // 证明了 换成数组 比 用字符串的 charAt 对比 速度快，内存小
    // 优先使用 动态规划
    public static String method(String s) {

        if (s == null || s.length() == 0) {
            return null;
        }

        int start = 0, end = 0;
        boolean[][] dp = new boolean[s.length()][s.length()];
        char[] arr = s.toCharArray();

        // 动态规划
        int max = 0;
        for (int length = 2; length <= arr.length; length++) {

            for (int j = 0; j < s.length(); j++) {
                int left = j;
                int right = j + length - 1;

                if (right >= s.length()) {
                    break;
                }
                if (arr[left] == arr[right]) {
                    if (right - left <= 2) {
                        dp[left][right] = true;
                    } else {
                        dp[left][right] = dp[left + 1][right - 1];
                    }
                }
                if (dp[left][right] && right - left + 1 > max) {
                    start = left;
                    end = right;
                }
            }
        }
        return s.substring(start, end + 1);
    }


    public String method2(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }

        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length - 1; i++) {
            process(arr, i, i); // 奇数
            process(arr, i, i + 1); // 偶数
        }

        return s.substring(start, end + 1);
    }

    public void process(char[] arr, int left, int right) {
        if (arr[left] != arr[right]) {
            return;
        }
        // 2 0 4
        while (left > 0 && right < arr.length - 1) {
            if (arr[left - 1] == arr[right + 1]) {
                left = left - 1;
                right = right + 1;
            } else {
                break;
            }
        }

        if (right - left + 1 > maxLen) {
            start = left;
            end = right;
            maxLen = right - left + 1;
        }
    }
}
